package com.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.store.domain.R;
import com.store.domain.entity.Address;
import com.store.domain.entity.User;
import com.store.domain.vo.AddressVo;
import com.store.mapper.AddressMapper;
import com.store.mapper.UserMapper;
import com.store.service.AddressService;
import com.store.utils.BeanCopyUtils;
import com.store.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 收货地址表(Address)表服务实现类
 *
 * @author yu
 * @since 2024-06-26 01:12:42
 */
@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Resource
    private UserMapper userMapper;

    @Override
    public R getMyAllAddress() {
        Integer userId = ThreadLocalUtil.getLocal();
        User user = userMapper.selectById(userId);
        LambdaQueryWrapper<Address> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Address::getUserId, userId);
        List<Address> list = list(lambdaQueryWrapper);
        List<AddressVo> addressVos = BeanCopyUtils.copyBeanList(list, AddressVo.class);
        for (AddressVo addressVo : addressVos){
            if(user.getDefaultAddressId().equals(addressVo.getId())){
                addressVo.setDefaultValue(true);
            } else {
                addressVo.setDefaultValue(false);
            }
        }
        return R.success(addressVos);
    }

    @Override
    public R addAddress(Address address) {
        Integer userId = ThreadLocalUtil.getLocal();
        address.setUserId(userId);
        boolean save = save(address);
        if (save){
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    @Override
    public R deleteAddress(Integer id) {
        boolean b = removeById(id);
        if (b){
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    @Override
    public R updateAddress(Address address) {
        boolean b = updateById(address);
        if (b){
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    @Override
    public R cancelDefault(Integer id) {
        return null;
    }

    @Override
    public R setDefault(Integer id) {
        Integer userId = ThreadLocalUtil.getLocal();
        User user = userMapper.selectById(userId);
        user.setDefaultAddressId(id);
        int i = userMapper.updateById(user);
        if (i > 0){
            return R.success("设置成功");
        }
        return R.error("设置失败");
    }
}


